// registerLoginRouter.js
const express = require('express');
const bodyParser = require('body-parser');
const router = express.Router();
const { registerUser, verifyUserLogin } = require('../database/userdatabase');

// 模拟验证码存储
const verificationCodes = {};

// 生成验证码（简单示例，实际可使用更安全的方式）
function generateVerificationCode() {
    return Math.floor(100000 + Math.random() * 900000).toString();
}

// 发送验证码接口（可根据实际情况完善，如使用短信服务）
router.post('/sendVerificationCode', (req, res) => {
    try {
        const { phoneNumber } = req.body;
        if (!phoneNumber) {
            return res.status(400).json({
                success: false,
                message: '电话号码不能为空'
            });
        }
        const code = generateVerificationCode();
        verificationCodes[phoneNumber] = code;
        console.log(`验证码已发送至 ${phoneNumber}: ${code}`);
        res.json({
            success: true,
			code:code,
            message: '验证码已发送'
        });
    } catch (error) {
        console.error('发送验证码时出错:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误，请稍后重试'
        });
    }
});

// 注册接口
router.post('/register', async (req, res) => {
    try {
        const { birthday, gender, avatar, phoneNumber, username, password, verificationCode } = req.body;

        // 验证必填字段
        if (!username || !password || !phoneNumber || !verificationCode) {
            return res.status(400).json({
                success: false,
                message: '用户名、密码、电话号码和验证码为必填项'
            });
        }

        // 验证验证码
        if (verificationCodes[phoneNumber]!== verificationCode) {
            return res.status(400).json({
                success: false,
                message: '验证码错误'
            });
        }

        const newUser = await registerUser({
            birthday,
            gender,
            avatar,
            phoneNumber,
            username,
            password
        });

        if (!newUser) {
            return res.status(400).json({
                success: false,
                message: '用户名已存在'
            });
        }

        // 清除验证码
        delete verificationCodes[phoneNumber];

        res.json({
            success: true,
            message: '注册成功'
        });
    } catch (error) {
        console.error('用户注册时出错:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误，请稍后重试'
        });
    }
});

// 登录接口
router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;
        const user = await verifyUserLogin(username, password);
		console.log(username,'1')
        if (!user) {
            return res.status(401).json({
                success: false,
                message: '用户名或密码错误'
            });
        }
        res.json({
            success: true,
            message: '登录成功',
            user: {
                username: user.username
            }
        });
    } catch (error) {
        console.error('用户登录时出错:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误，请稍后重试'
        });
    }
});

module.exports = router;